<template>
  <div class="connection-browser h-full flex flex-col">
    <!-- 工具栏 -->
    <div class="browser-toolbar p-3 border-b border-gray-200">
      <div class="flex items-center justify-between">
        <h3 class="text-sm font-medium text-gray-800">数据库连接</h3>
        <div class="flex items-center space-x-1">
          <el-button
            class="toolbar-button"
            link
            size="small"
            @click="showNewConnectionDialog"
            title="新建连接"
          >
            <el-icon><Plus /></el-icon>
          </el-button>
          <el-button
            class="toolbar-button"
            link
            size="small"
            @click="refreshConnections"
            title="刷新"
            :loading="connectionStore.loading"
          >
            <el-icon><Refresh /></el-icon>
          </el-button>
        </div>
      </div>
    </div>

    <!-- 连接树 -->
    <div class="connection-tree flex-1 overflow-auto p-2">
      <el-tree
        ref="treeRef"
        :data="treeData"
        :props="treeProps"
        :expand-on-click-node="false"
        :default-expand-all="false"
        node-key="id"
        class="connection-tree-component"
        @node-click="handleNodeClick"
        @node-contextmenu="handleNodeContextMenu"
      >
        <template #default="{ data }">
          <div class="tree-node flex items-center w-full">
            <!-- 节点图标 -->
            <div class="node-icon-wrapper">
              <div v-if="data.type === 'connection'" :class="['node-icon', getConnectionIconClass(data)]">
                <el-icon>
                  <component :is="getConnectionIcon(data)" />
                </el-icon>
              </div>
              <div v-else :class="['node-icon', getNodeTypeClass(data)]">
                <el-icon>
                  <component :is="getNodeIcon(data)" />
                </el-icon>
              </div>
            </div>

            <!-- 连接状态指示器 -->
            <div
              v-if="data.type === 'connection'"
              :class="['connection-status', getConnectionStatusClass(data)]"
            ></div>

            <!-- 节点标签 -->
            <span class="node-label flex-1 truncate" :title="data.label">
              {{ data.label }}
            </span>

            <!-- 节点操作按钮 -->
            <div class="node-actions opacity-0 group-hover:opacity-100 transition-opacity">
              <el-button
                v-if="data.type === 'connection'"
                class="action-button"
                link
                size="small"
                @click.stop="toggleConnection(data)"
                :title="isConnected(data) ? '断开连接' : '连接'"
              >
                <el-icon>
                  <Link v-if="!isConnected(data)" />
                  <Close v-else />
                </el-icon>
              </el-button>
              
              <el-button
                v-if="data.type === 'table' || data.type === 'view'"
                class="action-button"
                link
                size="small"
                @click.stop="openTableData(data)"
                title="浏览数据"
              >
                <el-icon><View /></el-icon>
              </el-button>
              
              <el-button
                v-if="data.type === 'query'"
                class="action-button"
                link
                size="small"
                @click.stop="openSavedQuery(data)"
                title="打开查询"
              >
                <el-icon><Document /></el-icon>
              </el-button>
            </div>
          </div>
        </template>
      </el-tree>

      <!-- 空状态 -->
      <div v-if="connectionStore.connections.length === 0" class="empty-state">
        <div class="text-center py-8">
          <el-icon class="text-4xl text-gray-400 mb-4"><Coin /></el-icon>
          <p class="text-gray-500 mb-4">暂无数据库连接</p>
          <el-button type="primary" class="empty-state-button" @click="showNewConnectionDialog">
            <el-icon class="mr-1"><Plus /></el-icon>
            新建连接
          </el-button>
        </div>
      </div>
    </div>

    <!-- 新建连接对话框 -->
    <NewConnectionDialog
      v-model="showConnectionDialog"
      @success="handleConnectionCreated"
    />

    <!-- 编辑连接对话框 -->
    <EditConnectionDialog
      v-model="showEditDialog"
      :connection="editingConnection"
      @success="handleConnectionUpdated"
    />
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useConnectionStore, useDatabaseStore, useTabStore, useMenuStore } from '@/stores'
import { DatabaseTypes, getDatabaseTypeIcon, DatabaseService } from '@/services/database'
import { ElMessageBox, ElMessage, ElLoading } from 'element-plus'
import NewConnectionDialog from './NewConnectionDialog.vue'
import EditConnectionDialog from './EditConnectionDialog.vue'

const router = useRouter()
const connectionStore = useConnectionStore()
const databaseStore = useDatabaseStore()
const tabStore = useTabStore()
const menuStore = useMenuStore() // 使用全局菜单管理器

// 响应式数据
const treeRef = ref()
const showConnectionDialog = ref(false)
const showEditDialog = ref(false)
const editingConnection = ref(null)

// 树组件配置
const treeProps = {
  children: 'children',
  label: 'label',
  isLeaf: 'isLeaf'
}

// 计算属性
const treeData = computed(() => {
  return connectionStore.connections.map(connection => {
    const connectionStatus = connectionStore.getConnectionStatus(connection.id)
    const databases = connectionStatus.databases || []
    
    return {
      id: connection.id,
      label: connection.name,
      type: 'connection',
      connection,
      isLeaf: !connectionStatus.isConnected,
      children: connectionStatus.isConnected ? databases.map(db => ({
        id: `${connection.id}:${db.name}`,
        label: db.name,
        type: 'database',
        connection,
        database: db,
        isLeaf: false,
        children: [] // 懒加载子节点
      })) : []
    }
  })
})

// 方法
const showNewConnectionDialog = () => {
  showConnectionDialog.value = true
}

// 辅助函数：查找特定类型的祖先节点
const findAncestorNode = (nodeId, targetType) => {
  let node = treeRef.value.getNode(nodeId)
  while (node && node.data.type !== targetType) {
    node = node.parent
  }
  return node
}

// 辅助函数：获取节点的数据库信息
const getNodeDatabaseInfo = (data) => {
  if (!data) return null
  
  // 根据节点类型获取数据库信息
  switch (data.type) {
    case 'connection':
      return null
    case 'database':
      return {
        connectionId: data.connection.id,
        database: data.database.name
      }
    case 'category':
    case 'table':
    case 'view':
    case 'query':
      return {
        connectionId: data.connection.id,
        database: data.database.name
      }
    default:
      return null
  }
}

const refreshConnections = async () => {
  try {
    // 保存当前展开的节点
    const expandedNodeIds = []
    const saveExpandedNodes = () => {
      if (treeRef.value) {
        const store = treeRef.value.store
        Object.keys(store.nodesMap).forEach(nodeId => {
          const node = store.nodesMap[nodeId]
          if (node.expanded) {
            expandedNodeIds.push(nodeId)
          }
        })
      }
    }
    saveExpandedNodes()
    
    // 加载连接和状态
    await connectionStore.loadConnections()
    await connectionStore.refreshAllConnectionStatus()
    
    // 恢复展开状态
    await nextTick()
    expandedNodeIds.forEach(nodeId => {
      const node = treeRef.value.getNode(nodeId)
      if (node) {
        node.expand()
      }
    })
  } catch (error) {
    ElMessage.error('刷新连接失败: ' + error.message)
  }
}

const isConnected = (data) => {
  if (data.type !== 'connection') return false
  const status = connectionStore.getConnectionStatus(data.connection.id)
  return status.isConnected
}

const getConnectionIcon = (data) => {
  const iconMap = {
    [DatabaseTypes.MYSQL]: 'Coin',
    [DatabaseTypes.POSTGRESQL]: 'Coin',
    [DatabaseTypes.SQLITE]: 'Document',
    [DatabaseTypes.SQLSERVER]: 'Coin',
    [DatabaseTypes.DAMENG]: 'Coin'
  }
  return iconMap[data.connection.type] || 'Coin'
}

const getConnectionIconClass = (data) => {
  const status = connectionStore.getConnectionStatus(data.connection.id)
  if (status.isConnected) {
    return 'text-green-600'
  } else if (status.connecting) {
    return 'text-yellow-600'
  } else {
    return 'text-gray-400'
  }
}

const getConnectionStatusClass = (data) => {
  const status = connectionStore.getConnectionStatus(data.connection.id)
  if (status.isConnected) {
    return 'connected'
  } else if (status.connecting) {
    return 'connecting'
  } else {
    return 'disconnected'
  }
}

const getNodeIcon = (data) => {
  if (data.type === 'connection') {
    return getConnectionIcon(data)
  } else if (data.type === 'database') {
    return 'Coin'
  } else if (data.type === 'category') {
    if (data.category === 'tables') return 'Grid'
    if (data.category === 'views') return 'View'
    if (data.category === 'functions') return 'Operation'
    if (data.category === 'queries') return 'Document'
    return 'Folder'
  } else if (data.type === 'table') {
    return 'Grid'
  } else if (data.type === 'view') {
    return 'View'
  } else if (data.type === 'function') {
    return 'Operation'
  } else if (data.type === 'query') {
    return 'Document'
  }
  return 'Document'
}

const getNodeTypeClass = (data) => {
  if (data.type === 'database') {
    return 'text-blue-600'
  } else if (data.type === 'category') {
    if (data.category === 'tables') return 'text-green-600'
    if (data.category === 'views') return 'text-purple-600'
    if (data.category === 'functions') return 'text-orange-600'
    if (data.category === 'queries') return 'text-blue-500'
    return 'text-gray-600'
  } else if (data.type === 'table') {
    return 'text-green-600'
  } else if (data.type === 'view') {
    return 'text-purple-600'
  } else if (data.type === 'function') {
    return 'text-orange-600'
  } else if (data.type === 'query') {
    return 'text-blue-500'
  }
  return 'text-gray-600'
}

const handleNodeClick = async (data, node) => {
  if (data.type === 'connection') {
    if (!isConnected(data)) {
      await toggleConnection(data)
    }
  } else if (data.type === 'database') {
    // 懒加载数据库对象
    if (!node.loaded) {
      try {
        // 加载表和视图
        const tables = await DatabaseService.listTables(
          data.connection.id,
          data.database.name
        )
        
        // 创建分类节点
        const tableNode = {
          id: `${data.connection.id}:${data.database.name}:tables`,
          label: '表',
          type: 'category',
          connection: data.connection,
          database: data.database,
          category: 'tables',
          isLeaf: false,
          children: []
        }
        
        const viewNode = {
          id: `${data.connection.id}:${data.database.name}:views`,
          label: '视图',
          type: 'category',
          connection: data.connection,
          database: data.database,
          category: 'views',
          isLeaf: false,
          children: []
        }
        
        const functionNode = {
          id: `${data.connection.id}:${data.database.name}:functions`,
          label: '函数',
          type: 'category',
          connection: data.connection,
          database: data.database,
          category: 'functions',
          isLeaf: false,
          children: []
        }
        
        const queryNode = {
          id: `${data.connection.id}:${data.database.name}:queries`,
          label: '查询',
          type: 'category',
          connection: data.connection,
          database: data.database,
          category: 'queries',
          isLeaf: false,
          children: []
        }
        
        // 分类处理表和视图
        tables.forEach(table => {
          const nodeData = {
            id: `${data.connection.id}:${data.database.name}:${table.name}`,
            label: table.name,
            type: table.type === 'VIEW' ? 'view' : 'table',
            connection: data.connection,
            database: data.database,
            table,
            isLeaf: true
          }
          
          if (table.type === 'VIEW') {
            viewNode.children.push(nodeData)
          } else {
            tableNode.children.push(nodeData)
          }
        })
        
        // 添加最近的查询到查询节点
        // TODO: 实现查询历史功能
        // const recentQueries = databaseStore.getConnectionQueries(data.connection.id, 10)
        //   .filter(q => q.database === data.database.name)
        
        // recentQueries.forEach(query => {
        //   queryNode.children.push({
        //     id: `${data.connection.id}:${data.database.name}:query:${query.id}`,
        //     label: query.name || query.sql.substring(0, 30) + (query.sql.length > 30 ? '...' : ''),
        //     type: 'query',
        //     connection: data.connection,
        //     database: data.database,
        //     query,
        //     isLeaf: true
        //   })
        // })
        
        // 始终添加所有分类节点，不管是否有子节点
        const children = [tableNode, viewNode, functionNode, queryNode]
        
        // 给空的分类添加提示节点
        if (tableNode.children.length === 0) {
          tableNode.children.push({
            id: `${data.connection.id}:${data.database.name}:tables:empty`,
            label: '无表',
            type: 'empty',
            isLeaf: true
          })
        }
        
        if (viewNode.children.length === 0) {
          viewNode.children.push({
            id: `${data.connection.id}:${data.database.name}:views:empty`,
            label: '无视图',
            type: 'empty',
            isLeaf: true
          })
        }
        
        if (functionNode.children.length === 0) {
          functionNode.children.push({
            id: `${data.connection.id}:${data.database.name}:functions:empty`,
            label: '无函数',
            type: 'empty',
            isLeaf: true
          })
        }
        
        if (queryNode.children.length === 0) {
          queryNode.children.push({
            id: `${data.connection.id}:${data.database.name}:queries:empty`,
            label: '无查询记录',
            type: 'empty',
            isLeaf: true
          })
        }
        
        data.children = children
        node.loaded = true
      } catch (error) {
        ElMessage.error('加载数据库对象失败: ' + error.message)
      }
    }
  } else if (data.type === 'category') {
    // 分类节点逻辑
    if (data.category === 'functions' && data.children.length === 0) {
      // 如果是函数分类且为空，尝试加载函数
      ElMessage.info('暂不支持函数浏览')
    }
  } else if (data.type === 'table') {
    // 双击表打开数据浏览
    openTableData(data)
  } else if (data.type === 'view') {
    // 双击视图打开数据浏览
    openTableData(data)
  } else if (data.type === 'query') {
    // 双击查询打开查询编辑器
    openSavedQuery(data)
  }
}

// 组件挂载时添加全局事件监听
onMounted(() => {
  // 只需要在组件挂载时加载连接，不需要额外的事件监听
  refreshConnections()
  
  // 监听导入成功事件，刷新表数据
  import('@wailsio/runtime').then(({ Events }) => {
    Events.On('refresh:table-data', async (data) => {
      console.log('Received refresh:table-data event:', data)
      
      // 查找对应的数据库节点并刷新
      const nodeId = `${data.connectionId}:${data.database}`
      const databaseNode = treeRef.value?.getNode(nodeId)
      
      if (databaseNode) {
        // 刷新数据库节点
        await refreshDatabase(databaseNode.data)
        ElMessage.success('表数据已刷新')
      }
    })
  }).catch(error => {
    console.log('Not in Wails environment or runtime not available:', error)
  })
})

// 组件销毁时清理
onUnmounted(() => {
  // 如果有菜单打开，关闭它
  if (menuStore.isVisible) {
    menuStore.closeMenu()
  }
  
  // 清理事件监听器
  import('@wailsio/runtime').then(({ Events }) => {
    Events.Off('refresh:table-data')
  }).catch(() => {
    // 忽略错误
  })
})

const handleNodeContextMenu = (event, data) => {
  // 阻止默认浏览器右键菜单
  event.preventDefault()
  event.stopPropagation()
  
  console.log('显示节点右键菜单:', {
    x: event.clientX,
    y: event.clientY,
    type: data.type,
    label: data.label
  })
  
  // 根据节点类型设置菜单类型
  let menuType = data.type
  if (data.type === 'category') {
    menuType = `category_${data.category}`
  }
  
  // 显示全局菜单
  menuStore.showMenu({
    type: menuType,
    data: data,
    x: event.clientX,
    y: event.clientY,
    onCommand: handleContextMenuCommand
  })
}

const handleContextMenuCommand = async (command, data) => {
  if (!data) return

  console.log('处理菜单命令:', command, data.type)

  switch (command) {
    case 'connect':
      await toggleConnection(data)
      break
    case 'disconnect':
      await disconnectConnection(data)
      break
    case 'newQuery':
      createNewQuery(data)
      break
    case 'createDatabase':
      createDatabase(data)
      break
    case 'edit':
      editConnection(data)
      break
    case 'delete':
      deleteConnection(data)
      break
    case 'browseData':
      openTableData(data)
      break
    case 'designTable':
      designTable(data)
      break
    case 'viewAllTables':
      viewAllTables(data)
      break
    case 'refresh':
      if (data.type === 'database') {
        await refreshDatabase(data)
      } else if (data.type === 'category') {
        // 刷新分类
        await refreshCategory(data)
      } else if (data.type === 'table') {
        // 刷新表
        await refreshTable(data)
      }
      break
    case 'openQuery':
      openSavedQuery(data)
      break
    case 'truncateTable':
      truncateTable(data)
      break
    case 'deleteTable':
      deleteTable(data)
      break
    case 'renameTable':
      renameTable(data)
      break
    case 'copyTableName':
      copyTableName(data)
      break
    case 'importData':
      importData(data)
      break
  }
}

const toggleConnection = async (data) => {
  try {
    if (isConnected(data)) {
      await connectionStore.disconnectFromDatabase(data.connection.id)
    } else {
      await connectionStore.connectToDatabase(data.connection.id)
    }
  } catch (error) {
    ElMessage.error('连接操作失败: ' + error.message)
  }
}

const disconnectConnection = async (data) => {
  try {
    await connectionStore.disconnectFromDatabase(data.connection.id)
  } catch (error) {
    ElMessage.error('断开连接失败: ' + error.message)
  }
}

const createNewQuery = (data) => {
  const connectionId = data.connection.id
  
  // 根据节点类型获取数据库名称
  let databaseName = null
  
  if (data.type === 'database') {
    // 数据库节点
    databaseName = data.database.name
  } else if (data.type === 'table') {
    // 表节点
    databaseName = data.database.name
  }
  
  // 创建查询标签，同时传递数据库名称
  tabStore.createQueryTab(connectionId, {
    database: databaseName, // 确保database字段被设置
    title: databaseName ? `${databaseName} - 查询` : '新建查询'
  })
}

const editConnection = (data) => {
  editingConnection.value = data.connection
  showEditDialog.value = true
}

const deleteConnection = async (data) => {
  try {
    // 检查是否为默认连接
    const isDefault = data.connection.isDefault;
    let warningMsg = `确定要删除连接 "${data.connection.name}" 吗？`;
    
    if (isDefault) {
      warningMsg += "\n\n⚠️ 注意：这是一个默认连接，删除后需要重新设置默认连接。";
    }
    
    // 检查连接是否有相关标签页
    const relatedTabs = tabStore.tabs.filter(
      tab => tab.connectionId === data.connection.id
    );
    
    if (relatedTabs.length > 0) {
      warningMsg += `\n\n删除此连接将关闭 ${relatedTabs.length} 个相关标签页。`;
    }
    
    // 使用更强的确认对话框
    await ElMessageBox.confirm(
      warningMsg,
      '确认删除连接',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消操作',
        confirmButtonClass: 'el-button--danger',
        type: 'warning',
        dangerouslyUseHTMLString: true,
        showClose: true,
        closeOnClickModal: false,
        closeOnPressEscape: true,
        distinguishCancelAndClose: true,
        draggable: true,
        customClass: 'connection-delete-confirm'
      }
    )
    
    // 显示全屏加载
    const loading = ElLoading.service({
      lock: true,
      text: '正在删除连接...',
      background: 'rgba(255, 255, 255, 0.8)'
    });
    
    try {
      // 1. 如果连接是打开状态，先断开连接
      if (isConnected(data)) {
        await connectionStore.disconnectFromDatabase(data.connection.id);
      }
      
      // 2. 关闭与此连接相关的所有标签页
      for (const tab of relatedTabs) {
        tabStore.closeTab(tab.id);
      }
      
      // 3. 删除连接 - 使用超时处理
      const deletePromise = connectionStore.deleteConnection(data.connection.id);
      
      // 设置10秒超时
      const timeoutPromise = new Promise((_, reject) => {
        setTimeout(() => reject(new Error('删除操作超时')), 10000);
      });
      
      await Promise.race([deletePromise, timeoutPromise]);
      
      ElMessage({
        type: 'success',
        message: '连接删除成功',
        duration: 2000
      });
    } catch (error) {
      console.error('删除连接时出错:', error);
      ElMessage.error('删除连接失败: ' + error.message);
    } finally {
      // 确保加载状态被关闭
      loading.close();
      
      // 刷新连接列表，确保UI状态一致
      await connectionStore.loadConnections();
    }
  } catch (error) {
    if (error === 'cancel' || error === 'close') {
      // 用户取消删除，不显示错误
      return;
    }
    ElMessage.error('删除连接失败: ' + error.message);
  }
}

const openTableData = (data) => {
  tabStore.createBrowseTab(
    data.connection.id,
    data.database.name,
    data.table.name
  )
}

const designTable = (data) => {
  // 添加调试信息
  console.log('designTable called with data:', data);
  
  // 提取连接ID，处理不同的数据结构
  let connectionId = null;
  let database = null;
  let table = null;
  
  if (data.connection && data.connection.id) {
    // 标准结构
    connectionId = data.connection.id;
    database = data.database?.name;
    table = data.table?.name;
  } else if (data.connectionId) {
    // 替代结构
    connectionId = data.connectionId;
    database = data.database;
    table = data.name || data.table;
  } else if (data.type === 'table') {
    // TableBrowser 使用的结构
    connectionId = data.connection?.id;
    database = data.database?.name;
    table = data.name;
  }
  
  if (!connectionId) {
    console.error('Invalid data for table design, missing connection ID:', data);
    ElMessage.error('无法设计表：缺少连接ID');
    return;
  }
  
  if (!database) {
    console.error('Invalid data for table design, missing database:', data);
    ElMessage.error('无法设计表：缺少数据库名');
    return;
  }
  
  if (!table) {
    console.error('Invalid data for table design, missing table name:', data);
    ElMessage.error('无法设计表：缺少表名');
    return;
  }
  
  console.log('Creating design tab with:', { connectionId, database, table });
  
  tabStore.createDesignTab(
    connectionId,
    database,
    table
  );
}

const refreshDatabase = async (data) => {
  try {
    // 刷新数据库的表列表
    await DatabaseService.listTables(
      data.connection.id,
      data.database.name
    )
    
    // 找到数据库节点并重新加载其子节点
    const node = treeRef.value.getNode(data.id)
    if (node) {
      // 保存展开状态
      const expandedNodes = []
      const saveExpandedState = (node) => {
        if (node.expanded) {
          expandedNodes.push(node.data.id)
        }
        if (node.childNodes) {
          node.childNodes.forEach(saveExpandedState)
        }
      }
      saveExpandedState(node)
      
      // 标记为未加载，然后重新加载
      node.loaded = false
      node.data.children = []
      
      // 重新触发加载
      await handleNodeClick(node.data, node)
      
      // 恢复展开状态
      await nextTick()
      expandedNodes.forEach(nodeId => {
        const expandNode = treeRef.value.getNode(nodeId)
        if (expandNode) {
          expandNode.expand()
        }
      })
      
      ElMessage.success('数据库刷新成功')
    }
  } catch (error) {
    ElMessage.error('刷新失败: ' + error.message)
  }
}

const handleConnectionCreated = (connection) => {
  ElMessage.success(`连接 "${connection.name}" 创建成功`)
}

const handleConnectionUpdated = (connection) => {
  ElMessage.success(`连接 "${connection.name}" 更新成功`)
}

const openSavedQuery = (data) => {
  if (!data.query) return
  
  tabStore.createQueryTab(data.connection.id, {
    database: data.database.name,
    title: `${data.database.name} - ${data.query.name || '查询'}`,
    sql: data.query.sql
  })
}

// 查看全部表
const viewAllTables = (data) => {
  if (!data || data.type !== 'category' || data.category !== 'tables') return
  
  // 获取该数据库中的所有表
  const tableNodes = data.children.filter(node => node.type === 'table')
  
  if (tableNodes.length === 0) {
    ElMessage.info('该数据库没有表')
    return
  }
  
  // 创建一个显示所有表的标签页
  tabStore.createTableBrowserTab(
    data.connection.id,
    data.database.name,
    {
      title: `${data.database.name} - 全部表`,
      tables: tableNodes.map(node => node.table?.name).filter(Boolean)
    }
  )
}

// 刷新表
const refreshTable = async (data) => {
  try {
    // 找到数据库节点
    const databaseNode = findAncestorNode(data.id, 'database')
    if (!databaseNode) {
      throw new Error('找不到数据库节点')
    }
    
    // 获取数据库信息
    const dbInfo = getNodeDatabaseInfo(data)
    if (!dbInfo) {
      throw new Error('无法获取数据库信息')
    }
    
    // 刷新数据库的表列表
    await DatabaseService.listTables(
      dbInfo.connectionId,
      dbInfo.database
    )
    
    // 保存数据库节点的展开状态
    const expandedCategories = []
    databaseNode.childNodes.forEach(child => {
      if (child.expanded) {
        expandedCategories.push(child.data.category)
      }
    })
    
    // 重新加载数据库节点
    databaseNode.loaded = false
    databaseNode.data.children = []
    await handleNodeClick(databaseNode.data, databaseNode)
    
    // 恢复展开状态
    await nextTick()
    databaseNode.childNodes.forEach(child => {
      if (expandedCategories.includes(child.data.category)) {
        child.expand()
      }
    })
    
    ElMessage.success(`表 "${data.table.name}" 刷新成功`)
  } catch (error) {
    ElMessage.error(`刷新表失败: ${error.message}`)
  }
}

// 刷新分类节点
const refreshCategory = async (data) => {
  try {
    // 找到数据库节点
    const databaseNode = findAncestorNode(data.id, 'database')
    if (!databaseNode) {
      throw new Error('找不到数据库节点')
    }
    
    // 获取数据库信息
    const dbInfo = getNodeDatabaseInfo(data)
    if (!dbInfo) {
      throw new Error('无法获取数据库信息')
    }
    
    // 刷新数据库的表列表
    await DatabaseService.listTables(
      dbInfo.connectionId,
      dbInfo.database
    )
    
    // 保存当前分类的展开状态
    const categoryNode = treeRef.value.getNode(data.id)
    const wasExpanded = categoryNode?.expanded
    
    // 重新加载数据库节点
    databaseNode.loaded = false
    databaseNode.data.children = []
    await handleNodeClick(databaseNode.data, databaseNode)
    
    // 恢复分类的展开状态
    await nextTick()
    const newCategoryNode = treeRef.value.getNode(data.id)
    if (newCategoryNode && wasExpanded) {
      newCategoryNode.expand()
    }
    
    ElMessage.success(`${data.label}刷新成功`)
  } catch (error) {
    ElMessage.error(`刷新失败: ${error.message}`)
  }
}

// 清空表
const truncateTable = async (data) => {
  if (!data || data.type !== 'table') return
  
  try {
    const tableName = data.table.name
    const databaseName = data.database.name
    const connectionId = data.connection.id
    
    // 确认对话框
    await ElMessageBox.confirm(
      `确定要清空表 "${tableName}" 中的所有数据吗？此操作不可恢复！`,
      '清空表',
      {
        confirmButtonText: '确认清空',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    // 使用专门的 truncateTable 方法
    await DatabaseService.truncateTable(connectionId, databaseName, tableName)
    
    ElMessage.success(`表 "${tableName}" 已清空`)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`清空表失败: ${error.message || error}`)
    }
  }
}

// 删除表
const deleteTable = async (data) => {
  if (!data || data.type !== 'table') return
  
  try {
    const tableName = data.table.name
    const databaseName = data.database.name
    const connectionId = data.connection.id
    
    // 确认对话框
    await ElMessageBox.confirm(
      `确定要删除表 "${tableName}" 吗？此操作将永久删除表及其所有数据，不可恢复！`,
      '删除表',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger',
        dangerouslyUseHTMLString: true
      }
    )
    
    // 使用专门的 dropTable 方法
    await DatabaseService.dropTable(connectionId, databaseName, tableName, false)
    
    ElMessage.success(`表 "${tableName}" 已删除`)
    
    // 关闭与此表相关的所有标签页
    const relatedTabs = tabStore.tabs.filter(tab => 
      tab.connectionId === connectionId &&
      tab.database === databaseName &&
      tab.table === tableName
    )
    
    for (const tab of relatedTabs) {
      tabStore.closeTab(tab.id)
    }
    
    // 刷新数据库节点以更新表列表
    try {
      const databaseNode = findAncestorNode(data.id, 'database')
      if (databaseNode) {
        await refreshDatabase(databaseNode.data)
      }
    } catch (refreshError) {
      // 如果刷新失败，至少要重新加载表列表
      // 激活该连接和数据库以确保可以调用 refreshTables
      await connectionStore.connectToDatabase(connectionId)
      await databaseStore.selectDatabase(databaseName)
      await databaseStore.refreshTables()
      console.error('刷新树节点失败:', refreshError)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`删除表失败: ${error.message || error}`)
    }
  }
}

// 修改表名
const renameTable = async (data) => {
  if (!data || data.type !== 'table') return
  
  try {
    const oldName = data.table.name
    const databaseName = data.database.name
    const connectionId = data.connection.id
    
    // 弹出输入框
    const { value: newName } = await ElMessageBox.prompt(
      '请输入新的表名',
      '修改表名',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        inputValue: oldName,
        inputValidator: (value) => {
          if (!value) {
            return '表名不能为空'
          }
          if (value === oldName) {
            return '新表名与原表名相同'
          }
          return true
        }
      }
    )
    
    if (newName && newName !== oldName) {
      // 使用专门的 renameTable 方法
      await DatabaseService.renameTable(connectionId, databaseName, oldName, newName)
      
      ElMessage.success(`表已重命名为 "${newName}"`)
      
      // 刷新数据库节点以更新表列表
      try {
        const databaseNode = findAncestorNode(data.id, 'database')
        if (databaseNode) {
          await refreshDatabase(databaseNode.data)
        }
      } catch (refreshError) {
        // 如果刷新失败，至少要重新加载表列表
        // 激活该连接和数据库以确保可以调用 refreshTables
        await connectionStore.connectToDatabase(connectionId)
        await databaseStore.selectDatabase(databaseName)
        await databaseStore.refreshTables()
        console.error('刷新树节点失败:', refreshError)
      }
      
      // 更新相关标签页的标题
      const relatedTabs = tabStore.tabs.filter(tab => 
        tab.connectionId === connectionId &&
        tab.database === databaseName &&
        tab.table === oldName
      )
      
      for (const tab of relatedTabs) {
        // 更新标签页的表名
        tab.table = newName
        if (tab.title.includes(oldName)) {
          tab.title = tab.title.replace(oldName, newName)
        }
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`修改表名失败: ${error.message || error}`)
    }
  }
}

// 复制表名
const copyTableName = (data) => {
  if (!data || data.type !== 'table') return
  
  const tableName = data.table.name
  
  // 使用Clipboard API复制文本
  navigator.clipboard.writeText(tableName)
    .then(() => {
      ElMessage.success(`表名 "${tableName}" 已复制到剪贴板`)
    })
    .catch(err => {
      ElMessage.error(`复制失败: ${err.message}`)
    })
}

// 导入数据
const importData = async (data) => {
  if (!data || data.type !== 'table') return
  
  try {
    const tableName = data.table.name
    const databaseName = data.database.name
    const connectionId = data.connection.id
    const connectionType = data.connection.type
    
    // 创建导入配置
    const importConfig = {
      connectionId,
      connectionType,
      database: databaseName,
      table: tableName,
      // 传递表的结构信息，用于字段映射
      columns: []
    }
    
    // 获取表的列信息
    try {
      const columns = await DatabaseService.getTableColumns(connectionId, databaseName, tableName)
      importConfig.columns = columns
    } catch (error) {
      console.error('获取表结构失败:', error)
    }
    
    // 调用后端API创建导入窗口
    // 使用 Wails3 的多窗口功能创建新窗口
    await openImportWindow(importConfig)
    
    ElMessage.info(`正在打开表 "${tableName}" 的数据导入窗口...`)
  } catch (error) {
    ElMessage.error(`打开导入窗口失败: ${error.message || error}`)
  }
}

// 打开导入窗口
const openImportWindow = async (config) => {
  try {
    // 使用窗口服务创建导入窗口
    const { WindowService } = await import('@/services/window')
    const result = await WindowService.createImportWindow(config)
    
    if (result.error) {
      throw new Error(result.error)
    }
    
    console.log('Import window created:', result)
    
    return result
  } catch (error) {
    console.error('创建导入窗口失败:', error)
    throw error
  }
}

// 创建数据库
const createDatabase = async (data) => {
  if (!data || data.type !== 'connection') return
  
  try {
    const connectionId = data.connection.id
    const connectionType = data.connection.type
    
    // SQLite 不支持创建数据库
    if (connectionType === 'SQLite') {
      ElMessage.warning('SQLite 不支持创建数据库，数据库文件在首次连接时自动创建')
      return
    }
    
    // 根据数据库类型选择提示文本
    const inputLabel = connectionType === 'PostgreSQL' ? '请输入新模式名称' : '请输入新数据库名称'
    const dialogTitle = connectionType === 'PostgreSQL' ? '创建模式' : '创建数据库'
    
    // 弹出输入框
    const { value: databaseName } = await ElMessageBox.prompt(
      inputLabel,
      dialogTitle,
      {
        confirmButtonText: '创建',
        cancelButtonText: '取消',
        inputValidator: (value) => {
          if (!value || !value.trim()) {
            return connectionType === 'PostgreSQL' ? '模式名不能为空' : '数据库名不能为空'
          }
          // 验证数据库名称格式
          const validPattern = /^[a-zA-Z][a-zA-Z0-9_]*$/
          if (!validPattern.test(value)) {
            return '名称必须以字母开头，只能包含字母、数字和下划线'
          }
          return true
        }
      }
    )
    
    if (databaseName) {
      // 显示加载状态
      const loading = ElLoading.service({
        lock: true,
        text: connectionType === 'PostgreSQL' ? '正在创建模式...' : '正在创建数据库...',
        background: 'rgba(255, 255, 255, 0.8)'
      })
      
      try {
        // 根据数据库类型构造创建语句
        let createSQL = ''
        switch (connectionType) {
          case 'PostgreSQL':
            createSQL = `CREATE SCHEMA IF NOT EXISTS "${databaseName}"`
            break
          case 'MySQL':
            createSQL = `CREATE DATABASE IF NOT EXISTS \`${databaseName}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`
            break
          case 'SQLServer':
            createSQL = `CREATE DATABASE [${databaseName}]`
            break
          case 'DaMeng':
            createSQL = `CREATE SCHEMA "${databaseName}"`
            break
          default:
            createSQL = `CREATE DATABASE ${databaseName}`
        }
        
        // 执行创建数据库的SQL
        await DatabaseService.executeNonQuery(connectionId, createSQL)
        
        ElMessage.success(
          connectionType === 'PostgreSQL' 
            ? `模式 "${databaseName}" 创建成功` 
            : `数据库 "${databaseName}" 创建成功`
        )
        
        // 刷新连接以显示新创建的数据库
        await refreshConnections()
      } catch (error) {
        // 处理特定的错误消息
        let errorMessage = error.message || error
        
        // 检查是否是权限问题
        if (errorMessage.includes('permission') || errorMessage.includes('denied')) {
          errorMessage = '权限不足，无法创建数据库'
        } else if (errorMessage.includes('exists') || errorMessage.includes('already')) {
          errorMessage = connectionType === 'PostgreSQL' 
            ? `模式 "${databaseName}" 已存在` 
            : `数据库 "${databaseName}" 已存在`
        }
        
        ElMessage.error(`创建失败: ${errorMessage}`)
      } finally {
        loading.close()
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`操作失败: ${error.message || error}`)
    }
  }
}
</script>

<style scoped>
.connection-browser {
  user-select: none;
  background-color: #f8fafc;
  display: flex;
  flex-direction: column;
  height: 100%;
  border-right: 1px solid rgba(226, 232, 240, 0.8);
}

.browser-toolbar {
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(8px);
  padding: 12px 16px;
  border-bottom: 1px solid rgba(226, 232, 240, 0.8);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.02);
  position: sticky;
  top: 0;
  z-index: 10;
}

.browser-toolbar h3 {
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
}

.connection-tree {
  padding: 8px;
  flex: 1;
  overflow: auto;
}

:deep(.connection-tree-component) {
  background: transparent;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

:deep(.el-tree) {
  --el-tree-node-hover-bg-color: rgba(236, 244, 254, 0.7);
  --el-tree-node-content-height: 36px;
}

:deep(.el-tree-node) {
  margin-bottom: 4px;
  transition: all 0.3s ease;
}

:deep(.el-tree-node__content) {
  height: 36px;
  border-radius: 8px;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  padding-right: 4px;
}

:deep(.el-tree-node__content:hover) {
  background-color: rgba(236, 244, 254, 0.9) !important;
  transform: translateX(2px);
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: rgba(219, 234, 254, 0.9) !important;
  color: #2563eb;
  font-weight: 500;
  box-shadow: 0 1px 2px rgba(30, 64, 175, 0.1);
}

:deep(.el-tree-node__expand-icon) {
  color: #64748b;
  transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
}

:deep(.el-tree-node__expand-icon.expanded) {
  transform: rotate(90deg) scale(1.1);
}

.tree-node {
  padding: 0 6px;
  width: 100%;
  display: flex;
  align-items: center;
  border-radius: 6px;
}

.node-icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  margin-right: 6px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.node-icon {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.3s ease;
}

:deep(.el-tree-node__content:hover) .node-icon {
  transform: scale(1.15);
}

:deep(.el-tree-node__content:active) .node-icon {
  transform: scale(0.95);
}

.node-label {
  font-size: 13px;
  line-height: 1.4;
  color: #334155;
  transition: color 0.2s ease;
}

:deep(.el-tree-node.is-current > .el-tree-node__content) .node-label {
  font-weight: 500;
  color: #1e40af;
}

.node-actions {
  display: flex;
  align-items: center;
  gap: 2px;
  transition: opacity 0.2s ease;
}

.node-actions :deep(.el-button) {
  padding: 4px;
  border-radius: 6px;
}

.node-actions :deep(.el-button:hover) {
  background-color: rgba(255, 255, 255, 0.8);
  color: #2563eb;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  min-height: 200px;
  color: #64748b;
  text-align: center;
  padding: 32px;
  background: rgba(255, 255, 255, 0.5);
  border-radius: 12px;
  margin: 16px;
  backdrop-filter: blur(4px);
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05),
              0 2px 4px -1px rgba(0, 0, 0, 0.03);
}

.empty-state :deep(.el-icon) {
  font-size: 48px;
  color: #94a3b8;
  margin-bottom: 16px;
  filter: drop-shadow(0 4px 3px rgba(0, 0, 0, 0.07));
}

.empty-state p {
  margin-bottom: 20px;
  font-size: 15px;
  color: #64748b;
}

/* 滚动条样式 */
.connection-tree::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.connection-tree::-webkit-scrollbar-track {
  background: transparent;
  border-radius: 3px;
}

.connection-tree::-webkit-scrollbar-thumb {
  background: rgba(203, 213, 225, 0.8);
  border-radius: 3px;
  transition: background 0.2s ease;
}

.connection-tree::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

/* 连接状态指示器 */
.connection-status {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 6px;
  position: relative;
}

.connection-status.connected {
  background-color: #10b981;
  box-shadow: 0 0 0 2px rgba(16, 185, 129, 0.2);
}

.connection-status.connected::after {
  content: '';
  position: absolute;
  top: -2px;
  left: -2px;
  right: -2px;
  bottom: -2px;
  border-radius: 50%;
  background: rgba(16, 185, 129, 0.4);
  animation: pulse-green 2s infinite ease-in-out;
}

.connection-status.connecting {
  background-color: #f59e0b;
  box-shadow: 0 0 0 2px rgba(245, 158, 11, 0.2);
  animation: pulse-yellow 1.5s infinite ease-in-out;
}

.connection-status.disconnected {
  background-color: #cbd5e1;
  box-shadow: 0 0 0 2px rgba(203, 213, 225, 0.2);
}

@keyframes pulse-green {
  0% {
    transform: scale(1);
    opacity: 0.8;
  }
  70% {
    transform: scale(1.7);
    opacity: 0;
  }
  100% {
    transform: scale(1);
    opacity: 0;
  }
}

@keyframes pulse-yellow {
  0% {
    opacity: 0.6;
    transform: scale(1);
  }
  50% {
    opacity: 1;
    transform: scale(1.2);
  }
  100% {
    opacity: 0.6;
    transform: scale(1);
  }
}

/* 节点图标颜色 */
.text-green-600 {
  color: #059669;
}

.text-blue-600 {
  color: #2563eb;
}

.text-purple-600 {
  color: #9333ea;
}

.text-orange-600 {
  color: #ea580c;
}

.text-yellow-600 {
  color: #ca8a04;
}

.text-gray-400 {
  color: #94a3b8;
}

.text-blue-500 {
  color: #3b82f6;
}

.text-gray-600 {
  color: #475569;
}

/* 类型图标背景 */
:deep(.is-current) .node-icon {
  background-color: rgba(255, 255, 255, 0.7);
}

/* 展开动画 */
:deep(.el-tree-node__children) {
  transition: all 0.3s ease-out;
  overflow: hidden;
}

/* 暗色模式 */
@media (prefers-color-scheme: dark) {
  .toolbar-button:hover {
    background-color: rgba(30, 41, 59, 0.7);
  }
  
  .empty-state-button:hover {
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.3), 
                0 2px 4px -1px rgba(0, 0, 0, 0.2);
  }
  
  .connection-browser {
    background-color: #111827;
    border-right-color: rgba(55, 65, 81, 0.8);
  }
  
  .browser-toolbar {
    background: rgba(17, 24, 39, 0.8);
    border-bottom-color: rgba(55, 65, 81, 0.8);
  }
  
  .browser-toolbar h3 {
    color: #e5e7eb;
  }
  
  :deep(.el-tree) {
    --el-tree-node-hover-bg-color: rgba(30, 41, 59, 0.7);
  }
  
  :deep(.el-tree-node__content:hover) {
    background-color: rgba(30, 41, 59, 0.9) !important;
  }
  
  :deep(.el-tree-node.is-current > .el-tree-node__content) {
    background-color: rgba(30, 58, 138, 0.4) !important;
    color: #93c5fd;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
  }
  
  :deep(.el-tree-node__expand-icon) {
    color: #94a3b8;
  }
  
  .node-label {
    color: #e5e7eb;
  }
  
  :deep(.el-tree-node.is-current > .el-tree-node__content) .node-label {
    color: #93c5fd;
  }
  
  .node-actions :deep(.el-button:hover) {
    background-color: rgba(30, 41, 59, 0.8);
    color: #60a5fa;
  }
  
  .empty-state {
    background: rgba(17, 24, 39, 0.5);
    color: #94a3b8;
  }
  
  .empty-state :deep(.el-icon) {
    color: #64748b;
  }
  
  .empty-state p {
    color: #94a3b8;
  }
  
  .connection-tree::-webkit-scrollbar-thumb {
    background: rgba(55, 65, 81, 0.8);
  }
  
  .connection-tree::-webkit-scrollbar-thumb:hover {
    background: #4b5563;
  }
  
  .connection-status.disconnected {
    background-color: #4b5563;
    box-shadow: 0 0 0 2px rgba(75, 85, 99, 0.2);
  }
  
  /* 节点图标颜色调整 */
  .text-green-600 {
    color: #34d399;
  }
  
  .text-blue-600 {
    color: #60a5fa;
  }
  
  .text-purple-600 {
    color: #c084fc;
  }
  
  .text-orange-600 {
    color: #fb923c;
  }
  
  .text-yellow-600 {
    color: #fcd34d;
  }
  
  .text-gray-400 {
    color: #9ca3af;
  }
  
  .text-blue-500 {
    color: #3b82f6;
  }
  
  .text-gray-600 {
    color: #d1d5db;
  }
  
  :deep(.is-current) .node-icon {
    background-color: rgba(30, 41, 59, 0.7);
  }
}

.toolbar-button {
  border-radius: 6px;
  transition: all 0.2s ease;
}

.toolbar-button:hover {
  background-color: rgba(236, 244, 254, 0.9);
  transform: translateY(-1px);
}

.toolbar-button:active {
  transform: translateY(1px);
}

.action-button {
  border-radius: 6px;
  transition: all 0.2s ease;
  opacity: 0.7;
}

.action-button:hover {
  opacity: 1;
  transform: scale(1.1);
}

.action-button:active {
  transform: scale(0.95);
}

.empty-state-button {
  transition: all 0.3s ease;
  border-radius: 8px;
}

.empty-state-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 
              0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.empty-state-button:active {
  transform: translateY(1px);
}
</style>

<!-- 添加全局样式 -->
<style>
/* 删除确认对话框样式 */
.connection-delete-confirm .el-message-box__header {
  padding: 16px;
  background-color: #fef2f2;
  border-bottom: 1px solid #fee2e2;
}

.connection-delete-confirm .el-message-box__title {
  color: #b91c1c;
  font-weight: 600;
}

.connection-delete-confirm .el-message-box__message {
  padding: 16px;
  white-space: pre-line;
  font-size: 14px;
  line-height: 1.6;
}

.connection-delete-confirm .el-message-box__btns {
  padding: 12px 16px;
  border-top: 1px solid #e5e7eb;
}

.connection-delete-confirm .el-button--danger {
  background-color: #dc2626;
  border-color: #b91c1c;
}

.connection-delete-confirm .el-button--danger:hover {
  background-color: #b91c1c;
  border-color: #991b1b;
}

.connection-delete-confirm .el-message-box__status {
  font-size: 24px;
  color: #b91c1c;
}
</style> 